import 'package:flutter/material.dart';
import '../constants/colors.dart';
import '../constants/text_styles.dart';
import '../constants/spacing.dart';
import '../constants/dimensions.dart';
import '../mock_data/mock_data.dart';
import '../models/ai_pick_settings.dart';

/// AI挑图设置页面
///
/// 配置上传规则和各项图片检测功能
class AIPickSettingsScreen extends StatefulWidget {
  const AIPickSettingsScreen({super.key});

  /// 获取缓存的设置
  static AIPickSettings getCachedSettings() {
    return _AIPickSettingsScreenState._cachedSettings ??
        MockData.aiPickSettings;
  }

  @override
  State<AIPickSettingsScreen> createState() => _AIPickSettingsScreenState();
}

class _AIPickSettingsScreenState extends State<AIPickSettingsScreen> {
  // 使用静态变量保持设置状态，避免页面关闭后丢失
  static AIPickSettings? _cachedSettings;
  late AIPickSettings _settings;

  @override
  void initState() {
    super.initState();
    // 如果有缓存的设置则使用缓存，否则使用默认值
    _settings = _cachedSettings ?? MockData.aiPickSettings;
  }

  @override
  void dispose() {
    // 在页面销毁时保存当前设置
    _cachedSettings = _settings;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // 浅色主题背景
      backgroundColor: const Color(0xFFF2F4F7),
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leadingWidth: 48,
        leading: Padding(
          padding: const EdgeInsets.only(left: 8),
          child: IconButton(
            icon: const Icon(Icons.arrow_back_ios, size: 20),
            onPressed: () => Navigator.pop(context),
            color: const Color(0xFF181D28),
            padding: EdgeInsets.zero,
          ),
        ),
        titleSpacing: 0,
        title: const Text(
          'AI挑图设置',
          style: TextStyle(
            fontFamily: 'PingFang SC',
            fontSize: 16,
            fontWeight: FontWeight.w500,
            color: Color(0xFF181D28),
          ),
        ),
        centerTitle: false,
      ),
      body: Column(
        children: [
          Expanded(
            child: ListView(
              padding: const EdgeInsets.all(AppSpacing.md),
              children: [
                // 上传规则选择器
                _buildUploadRuleSelector(),

                const SizedBox(height: AppSpacing.md),

                // 检测设置卡片
                _buildDetectionSettingsCard(),
              ],
            ),
          ),

          // 底部应用按钮
          _buildApplyButton(),
        ],
      ),
    );
  }

  /// 构建上传规则选择器
  Widget _buildUploadRuleSelector() {
    return Container(
      padding: const EdgeInsets.all(AppSpacing.md),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '上传规则',
            style: TextStyle(
              fontFamily: 'PingFang SC',
              fontSize: 14,
              fontWeight: FontWeight.w500,
              color: Color(0xFF181D28),
            ),
          ),
          const SizedBox(height: AppSpacing.md),
          // 分段选择器
          _buildSegmentedControl(),
        ],
      ),
    );
  }

  /// 构建分段选择器
  Widget _buildSegmentedControl() {
    return Container(
      padding: const EdgeInsets.all(2),
      decoration: BoxDecoration(
        color: const Color(0xFFF2F4F7),
        borderRadius: BorderRadius.circular(4),
      ),
      child: Row(
        children: [
          Expanded(
            child: _buildSegmentItem(
              'AI挑图自动上传',
              UploadRule.aiFiltered,
            ),
          ),
          Expanded(
            child: _buildSegmentItem(
              '人工审核上传',
              UploadRule.manualSelection,
            ),
          ),
          Expanded(
            child: _buildSegmentItem(
              '免挑图直接上传',
              UploadRule.all,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建单个分段项
  Widget _buildSegmentItem(String label, UploadRule rule) {
    final isSelected = _settings.uploadRule == rule;

    return GestureDetector(
      onTap: () {
        setState(() {
          _settings = _settings.copyWith(uploadRule: rule);
        });
      },
      child: Container(
        padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 8),
        decoration: BoxDecoration(
          color: isSelected ? Colors.white : Colors.transparent,
          borderRadius: BorderRadius.circular(4),
        ),
        child: Center(
          child: Text(
            label,
            style: TextStyle(
              fontFamily: 'PingFang SC',
              fontSize: 11,
              fontWeight: FontWeight.w400,
              color: isSelected
                  ? const Color(0xFF181D28)
                  : const Color(0xFF667085),
            ),
            textAlign: TextAlign.center,
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
        ),
      ),
    );
  }

  /// 构建检测设置卡片
  Widget _buildDetectionSettingsCard() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        children: [
          _buildSettingItem(
            '重复照片检测',
            '自动过滤重复或相似的图片',
            Icons.content_copy_outlined,
            _settings.duplicateDetectionEnabled,
            (value) {
              setState(() {
                _settings =
                    _settings.copyWith(duplicateDetectionEnabled: value);
              });
            },
            showDivider: true,
          ),
          _buildSettingItem(
            '闭眼照片检测',
            '自动过滤人物闭眼的图片',
            Icons.visibility_off_outlined,
            _settings.eyesClosedDetectionEnabled,
            (value) {
              setState(() {
                _settings =
                    _settings.copyWith(eyesClosedDetectionEnabled: value);
              });
            },
            showDivider: true,
          ),
          _buildSettingItem(
            '过曝图片检测',
            '自动过滤过度曝光的图片',
            Icons.wb_sunny_outlined,
            _settings.overexposureDetectionEnabled,
            (value) {
              setState(() {
                _settings =
                    _settings.copyWith(overexposureDetectionEnabled: value);
              });
            },
            showDivider: true,
          ),
          _buildSettingItem(
            '欠曝图片检测',
            '自动过滤曝光不足的图片',
            Icons.brightness_low_outlined,
            _settings.underexposureDetectionEnabled,
            (value) {
              setState(() {
                _settings =
                    _settings.copyWith(underexposureDetectionEnabled: value);
              });
            },
            showDivider: true,
          ),
          _buildSettingItem(
            '图片清晰度检测',
            '自动过滤模糊不清的图片',
            Icons.blur_on_outlined,
            _settings.clarityDetectionEnabled,
            (value) {
              setState(() {
                _settings = _settings.copyWith(clarityDetectionEnabled: value);
              });
            },
            showDivider: false,
          ),
        ],
      ),
    );
  }

  /// 构建单个设置项
  Widget _buildSettingItem(
    String title,
    String subtitle,
    IconData icon,
    bool value,
    ValueChanged<bool> onChanged, {
    required bool showDivider,
  }) {
    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.symmetric(
            horizontal: AppSpacing.md,
            vertical: 12,
          ),
          child: Row(
            children: [
              // 图标
              Icon(
                icon,
                size: 16,
                color: const Color(0xFF181D28),
              ),
              const SizedBox(width: 8),
              // 文本内容
              Expanded(
                child: Text(
                  title,
                  style: const TextStyle(
                    fontFamily: 'PingFang SC',
                    fontSize: 14,
                    fontWeight: FontWeight.w500,
                    color: Color(0xFF181D28),
                  ),
                ),
              ),
              // 开关
              Switch(
                value: value,
                onChanged: onChanged,
                activeColor: AppColors.primary,
                activeTrackColor: AppColors.primary.withOpacity(0.5),
                inactiveThumbColor: Colors.white,
                inactiveTrackColor: const Color(0xFFE4E7EC),
              ),
            ],
          ),
        ),
        if (showDivider)
          const Padding(
            padding: EdgeInsets.only(left: AppSpacing.md),
            child: Divider(height: 1, thickness: 1, color: Color(0xFFF2F4F7)),
          ),
      ],
    );
  }

  /// 构建应用按钮
  Widget _buildApplyButton() {
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.all(AppSpacing.md),
      child: SafeArea(
        top: false,
        child: SizedBox(
          width: double.infinity,
          height: 48,
          child: ElevatedButton(
            onPressed: () {
              // 应用设置
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(
                  content: const Text('设置已应用'),
                  backgroundColor: AppColors.success,
                  behavior: SnackBarBehavior.floating,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                ),
              );
              Navigator.pop(context);
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: AppColors.primary,
              foregroundColor: Colors.white,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(24),
              ),
              elevation: 0,
            ),
            child: const Text(
              '应用',
              style: TextStyle(
                fontFamily: 'PingFang SC',
                fontSize: 16,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ),
      ),
    );
  }
}
